package yzx.fileutil.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import yzx.common.util.FileUtil;
import yzx.fileutil.R;
import yzx.fileutil.util.FileFinder;
import yzx.fileutil.util.ID;
import yzx.fileutil.util.Injector;
import yzx.fileutil.util.ToastUtil;


public class FileExchangeFragment extends Fragment {

    @ID(id=R.id.btn_select_folder)
    private View selectFolderBtn;
    @ID(id=R.id.btn_change)
    private View todoBtn;
    @ID(id=R.id.et_suffix)
    private EditText suffixInput;
    @ID(id=R.id.tv_selected_folder)
    private TextView selectedFolderTv;
    @ID(id=R.id.et_origin)
    private EditText originSuffixInput;

    private boolean isChanging = false;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_file_exchange, container, false);
        view.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Injector.injectField(this);
        /// 还原上次修改的路径
        String lastPath = getActivity().getSharedPreferences(sp_name, Context.MODE_PRIVATE).getString("value", null);
        if(lastPath != null)
            selectedFolderTv.setText(lastPath);
        /// 选择路径按钮点击
        selectFolderBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                final SingleFileSelectFragment f = new SingleFileSelectFragment();
                f.config.dismissRun=new Runnable() {
                    public void run() {
                        f.dismiss();
                        getChildFragmentManager().beginTransaction().remove(f).commitNow();
                    }
                };
                f.config.defaultFileIcon = R.mipmap.ic_launcher;
                f.config.showFile = false;
                f.config.directoryIcon = android.R.drawable.star_big_on;
                f.onFileSelectedListener = new SingleFileSelectFragment.OnFileSelectedListener() {
                    public void onSelected(File file) {
                        selectedFolderTv.setText(file.getAbsolutePath());
                    }
                };
                f.show(getChildFragmentManager(), f.getClass().getName());
            }
        });
        /// 修改按钮点击
        todoBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(isChanging)
                    return ;

                final String newSuffix = suffixInput.getText().toString().trim();
                if(newSuffix.isEmpty())return ;
                String selectedPath = selectedFolderTv.getText().toString().trim();
                if(selectedPath.isEmpty()) return ;
                String originSuffixText = originSuffixInput.getText().toString().trim();
                if(originSuffixText.isEmpty()) return ;

                File f = new File(selectedPath);
                if(!f.exists()){
                    ToastUtil.toast(getActivity(), "文件夹不存在了");
                    return ;
                }

                isChanging = true;
                final ProgressDialog pb = new ProgressDialog(getActivity());
                pb.setMessage("doing...");
                pb.setCancelable(false);
                pb.show();
                final ArrayList<String> selectOriginSuffixList = new ArrayList<>();
                selectOriginSuffixList.addAll(Arrays.asList(originSuffixText.split(",")));
                new FileFinder(f, new FileFinder.Filter() {
                    public boolean is(File file) {
                        String suffix = FileUtil.getSuffix(file).toLowerCase().trim();
                        if(suffix.isEmpty()) return false;
                        return selectOriginSuffixList.contains(suffix);
                    }
                }, new FileFinder.OnProgressListener() {
                    public void onComplete(List<File> list) {
                        for (File file : list)
                            reSuffix(file, newSuffix);
                        isChanging = false;
                        ToastUtil.toast(getActivity(),"over");
                        savePath();
                        pb.dismiss();
                    }
                    public void onFileFound(File file) {
                    }
                }).start();
            }
        });
    }

    /* 修改文件扩展名 */
    private void reSuffix(File file,String suffix){
        String name = FileUtil.getNameWithOutSuffix(file);
        name = name+"."+suffix;
        file.renameTo(new File(file.getParent(), name));
    }



    private final String sp_name = "last_selected_path.axa";
    private void savePath(){
        SharedPreferences sp = getActivity().getSharedPreferences(sp_name, Context.MODE_PRIVATE);
        sp.edit().putString("value", selectedFolderTv.getText().toString()).apply();
    }

}
